package com.shyroke.daydayzhuansvc.util;

import com.shyroke.daydayzhuanapi.entity.NewsEntity;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/25 12:11
 */
public class CommonUtil {

    public static List<String> spiderNameList ;

    static {
        spiderNameList = new ArrayList<>();
        spiderNameList.add("Baiduspider");
        spiderNameList.add("Googlebot");
        spiderNameList.add("360Spider");
        spiderNameList.add("Sosospider");
        spiderNameList.add("sogou spider");
        spiderNameList.add("YisouSpider");
        spiderNameList.add("Sogou web spider");
        spiderNameList.add("Bytespider");
        spiderNameList.add("AspiegelBot");
        spiderNameList.add("bingbot");
    }

    public static String getDateByFormat(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);

         return  sdf.format(date);
    }


    public static List<String> getImgSrcList(String content){
        List<String> list = new ArrayList<String>();
//目前img标签标示有3种表达式
//<img alt="" src="1.jpg"/> <img alt="" src="1.jpg"></img> <img alt="" src="1.jpg">
//开始匹配content中的<img />标签
        Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
//获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);
//开始匹配<img />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    String str_src = m_src.group(3);
                    list.add(str_src);
                }
//匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }
        return list;
    }


    /**
     * 防止特殊字符（括号、引号等）被转义
     * @param imgName
     * @return
     */
    public static String decode(String imgName) {

        if(imgName == null){
            return null;
        }

        String result;
        try {
            result = URLDecoder.decode(imgName,"utf-8");
        }catch (Exception e){
            throw new RuntimeException("转义失败");
        }

        return result;
    }

    public static String deleteOSSImgPre(String cover) {

        String pathPre = "http://"+OSSClientConstants.BUCKET_NAME+"."+OSSClientConstants.ENDPOINT+"/";
        String pathPre1 = "https://"+OSSClientConstants.BUCKET_NAME+"."+OSSClientConstants.ENDPOINT+"/";

        if(cover==null){
            return null;
        }

        if(cover.startsWith(pathPre)){
            cover = cover.replace(pathPre,"");
        }

        if(cover.startsWith(pathPre1)){
            cover = cover.replace(pathPre1,"");
        }
        return deleteOSSImgSuff(cover);
    }

    public static String deleteOSSImgSuff(String cover) {
        if(cover==null){
            return null;
        }
        if(cover.indexOf("?") != -1){
            cover = cover.substring(0,cover.indexOf("?"));
        }
        return cover;
    }

    public static boolean isSameDate(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);

        boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                .get(Calendar.YEAR);
        boolean isSameMonth = isSameYear
                && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
        boolean isSameDate = isSameMonth
                && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                .get(Calendar.DAY_OF_MONTH);

        return isSameDate;
    }


    /**
     * 将list平均分成list.size/pageSize份
     * @param list
     * @param pageSize
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitList(List<T>list, int pageSize) {
        int listSize = list.size();
        int page = (listSize + (pageSize - 1)) / pageSize;
        List<List<T>>listArray = new ArrayList<List<T>>();
        for (int i = 0; i<page; i++) {
            List<T> subList = new ArrayList<T>();
            for (int j = 0; j<listSize; j++) {
                int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;
                if (pageIndex == (i + 1)) {
                    subList.add(list.get(j));
                }
                if ((j + 1) == ((j + 1) * pageSize)) {
                    break;
                }
            }
            listArray.add(subList);
        }
        return listArray;
    }


    /**
     * 获取UUID
     * @return
     */
    public static  String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }


    /**
     * 获取图片后缀名
     * @param url
     * @return
     */
    public static String getImgSuff(String url) {

        if(url == null){
            return null;
        }

        int index = url.lastIndexOf(".");
        int attrIndex = url.lastIndexOf("?");
        if(attrIndex == -1){ //说明该路径没有参数
            return url.substring(index);
        }else{
            return url.substring(index,attrIndex);
        }

    }



    /**
     * 判断是否搜索引擎爬虫
     * @param request
     * @return
     */
    public static boolean isSpider(HttpServletRequest request) {

        String agent= request.getHeader("user-agent");

        for(String spiderName:spiderNameList){
            if(agent != null && agent.contains(spiderName)){
                return true;
            }
        }

        return false;

    }

    public static boolean in24Hour(Date date, Date createTime) {
        long cha = date.getTime() - createTime.getTime();
        if(cha<0){
            return false;
        }
        double result = cha * 1.0 / (1000 * 60 * 60);
        if(result<=24){
            return true;
        }else{
            return false;
        }

    }

    //判断Email合法性
    public static boolean isEmail(String email) {
        if (email == null)
            return false;
        String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        Pattern pattern;
        Matcher matcher;
        pattern = Pattern.compile(rule);
        matcher = pattern.matcher(email);
        if (matcher.matches())
            return true;
        else
            return false;
    }

    public static String getKeywordByContent(String content) {
        String[] contentArr = content.split("\\n\\n");
        return Arrays.toString(contentArr);
    }

//    public static void main(String[] args) {
////        String content = "1、为了批评世界及指正他人，我们生活才过得繁忙障碍，才会筋疲力尽。\n" +
////                "\n" +
////                "2、机会是靠自己争取的，成功是需要自己努力的。你，能行。\n" +
////                "\n" +
////                "3、乐观的人能重整旗鼓东山再起，悲观的人因缺乏自信，往往一败涂地。\n" +
////                "\n" +
////                "4、九州生气恃风雷，万马齐喑究可哀。我劝天公重抖擞，不拘一格降人才。\n" +
////                "\n" +
////                "5、为别人尽最大的力量，最后就是为自己尽最大的力量。\n" +
////                "\n" +
////                "6、青春去时不告别，老年来时不招手。\n" +
////                "\n" +
////                "7、平静的湖面，锻炼不出精悍的水手；安逸的生活打造不出时代的伟人。\n" +
////                "\n" +
////                "8、信心好比一粒种子，除非下种，否则不会结果。\n" +
////                "\n" +
////                "9、永远不要说如果，因为时光里没有如果。永远不要提后悔，因为人生经不起后悔。\n" +
////                "\n" +
////                "10、背负着过去的痛苦，夹杂着现实的烦恼，这对于人的心灵而言是无任何益处。\n" +
////                "\n" +
////                "11、眉毛上的汗水，眉毛下的泪水，你总得选一样。\n" +
////                "\n" +
////                "12、不要满足于眼前的小成就问问自己：我这辈子就这样了吗。\n" +
////                "\n" +
////                "13、你能否送我一块手帕？让我心上飘起一片帆。\n" +
////                "\n" +
////                "14、就算会彷徨，也还要去闯我要的幸福，在不远处我的骄傲无可救药。\n" +
////                "\n" +
////                "15、不要计较生命的长久，应该在乎过程是否够精彩。";
////        System.out.println(getKeywordByContent(content));
////    }

    public static NewsEntity createNews(String content,Integer userId,String type) {
        NewsEntity news = new NewsEntity();
        news.setDate(new Date());
        news.setIsRead(0);
        news.setContent(content);
        news.setType(type);
        news.setUserId(userId);
        return news;
    }

    /**
     * 根据Value降序
     * @param aMap
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
        HashMap<K, V> finalOut = new LinkedHashMap<>();
        aMap.entrySet()
                .stream()
                .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        return finalOut;
    }

    public static String getUrl(String requestURI) {
        return requestURI.endsWith("/")?requestURI.substring(0,requestURI.length()-1):requestURI;
    }
}
